package com.example.findfiledemo.service.impl;


import com.example.findfiledemo.entiy.ResponseObj;
import com.example.findfiledemo.service.AnyQService;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AnyQServiceImpl implements AnyQService {
    @Override
    //public ResponseObj question(String question) {
    public String question(String question) {
        Logger logger = LoggerFactory.getLogger(AnyQServiceImpl.class);

        // 向前端返回数据的对象
        ResponseObj result = new ResponseObj();

        Map<String,String> data = new HashMap<>(16);
        String requestUrl = "http://47.93.6.165:8999/anyq?question="+question;

        //查询坐席状态接口
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient client = builder.build();
        HttpGet post = new HttpGet( requestUrl );
        CloseableHttpResponse response = null;
        try {
            response = client.execute( post );
            StatusLine status = response.getStatusLine();
            int statusCode = status.getStatusCode();
            if(statusCode == 200){
                // 执行结果200
                HttpEntity entity = response.getEntity();
                String httpResult = EntityUtils.toString( entity, "utf8" );
                result.setCode("200");
                String anyqAnswer = getAnyqResponse(httpResult);
                data.put("answer",anyqAnswer);
            }else{
                // 设置返回的结果为404
                result.setCode("404");
                data.put("answer","未找到相关资料");
            }
            result.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String,String> map = new HashMap<>(16);

        map=result.getData();


        return map.get("answer");

    }

    /**
     * 从请求结果中获取答案
     * @param httpResponse http 执行结果
     * @return anyq 给出的答案
     */
    private String getAnyqResponse(String httpResponse){
        String[] split = httpResponse.split(",");
        String value = "";
        for (String str: split ) {
            if(str.contains("answer")){
                value = str.split(":")[1];
                break;
            }
        }

        String temp = unicodeToString(value);
        if("".equals(value)){
            temp = "\"未能找到答案\"";
        }
        return  temp.substring(1,temp.length()-1);
    }

    /**
     * unicode 转 utf-8字符串
     * @param str
     * @return
     */
    private static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            //group 6728
            String group = matcher.group(2);
            //ch:'木' 26408
            ch = (char) Integer.parseInt(group, 16);
            //group1 \u6728
            String group1 = matcher.group(1);
            str = str.replace(group1, ch + "");
        }
        return str;
    }
}
